"""Fix broken idmap ranges

Revision ID: f93329091a6f
Revises: 67ee25d22253
Create Date: 2023-01-17 15:29:52.743200+00:00

"""
from alembic import op
import sqlalchemy as sa


# revision identifiers, used by Alembic.
revision = 'f93329091a6f'
down_revision = '67ee25d22253'
branch_labels = None
depends_on = None


def upgrade():
    # This applies a DB change that may have been skipped during SCALE alpha / beta cycle.
    # The situation arose because we altered an existing migration between two pre-release versions
    # rather than writing a new migration.
    #
    # The first option is that this is a new upgrade from Angelfish (broken) to BlueFin. In this
    # case run the migration from NAS-111944.
    conn = op.get_bind()
    op.execute("""
        UPDATE directoryservice_idmap_domain SET idmap_domain_certificate_id = NULL WHERE idmap_domain_certificate_id = ''
    """)  # fixes break caused by fix to NAS-111944

    ranges = []
    default_range = (90000001, 100000000)

    for row in conn.execute("SELECT * FROM directoryservice_idmap_domain").fetchall():
        if row['id'] == 5:
            # The default domain entry wasn't dropped and so we can skip the rest of this
            return

        ranges.append((row['idmap_domain_range_low'], row['idmap_domain_range_high']))

    # Avoid colliding with any existing idmap ranges
    if any([default_range[0] in x or default_range[1] in x for x in [range(*r) for r in ranges]]):
        hwm = max([x[1] for x in ranges])
        default_range = (hwm + 1, hwm + 1000000)

    # Add the missing entry back
    new_entry = {
        'id': 5,
        'idmap_domain_name': 'DS_TYPE_DEFAULT_DOMAIN',
        'idmap_domain_idmap_backend': 'tdb',
        'idmap_domain_options': {},
        'idmap_domain_range_low': default_range[0],
        'idmap_domain_range_high': default_range[1],
    }

    conn.execute(
        f"INSERT INTO directoryservice_idmap_domain ({','.join(new_entry.keys())}) VALUES ({','.join(['?'] * len(new_entry))})",
        tuple(new_entry.values()),
    )


def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    pass
    # ### end Alembic commands ###
